package services

import (
	"fmt"

	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
)

var searcher *xdb.Searcher

// InitIPSearcher 初始化IP查询服务
func InitIPSearcher(dbPath string) error {
	var err error
	searcher, err = xdb.NewWithFileOnly(dbPath)
	if err != nil {
		return fmt.Errorf("初始化IP查询器失败: %v", err)
	}
	return nil
}

// CloseIPSearcher 关闭IP查询服务
func CloseIPSearcher() {
	if searcher != nil {
		searcher.Close()
	}
}

// SearchIP 查询IP地址的地理位置
func SearchIP(ip string) (string, error) {
	if searcher == nil {
		return "", fmt.Errorf("IP查询服务未初始化")
	}

	region, err := searcher.SearchByStr(ip)
	if err != nil {
		return "", err
	}
	return region, nil
}
